const {Article} = require('../../model/article')
//引入Joi模块
const Joi = require('joi')

const articles = async (req, res) => {
  //验证请求参数
  const schema = Joi.object({
    pagenum: Joi.number().min(1).integer().required().error(new Error('当前页码必须是正整数')),
    pagesize: Joi.number().min(1).integer().required().error(new Error('每页显示条数必须是正整数'))
  })
  const val = await schema.validate(req.body)
  if (val.error) {
    res.status(400).send({meta: {msg: val.error.toString().substring(7), status: 400}})
  } else {
    let articlesList = await Article.find().populate('author');
    //获取请求参数
    let pagenum = parseInt(req.body.pagenum);
    const pagesize = parseInt(req.body.pagesize);
    //获取总页数
    const totalpage = Math.floor(articlesList.length / req.body.pagesize);
    //pagenum大于总页数时，自动获取第一页数据
    if(pagenum > totalpage ) {
      pagenum = 1
    }
    //获取当前页数据
    articlesList = articlesList.slice((pagenum - 1) * pagesize, pagenum * pagesize);
    const resObj = {
      data: {
        totalpage,
        pagenum,
        articles: articlesList
      },
      meta: {
        msg: '获取成功',
        status: 200
      }
    }
    res.send(resObj)
  }
}

module.exports = articles;